<template>
  <bi-page class="risk-detail-page">
    <div class="risk-detail-page__main">
      <bi-county-symptom-list
        class="risk-detail-page__symptom"
        :data="result.divisionDataVos"
        :loading="shenzhenLoading"
        @item-click="handleDivisionItemClick"
      ></bi-county-symptom-list>
      <div class="isolation-wrapper">
        <div class="title-wrapper">
          <p>{{ panelTitleList[dataType] }}分类</p>
        </div>
        <div class="charts-content isolation" ref="isolation" v-loading="locationLoading"></div>
      </div>
      <div class="trend-wrapper">
        <div class="title-wrapper">
          <!-- <img src="../../../src/assets/images/trend-icon.png" alt=""> -->
          <p>{{ panelTitleList[dataType] }}趋势观测</p>
        </div>
        <chart-tabs
          class="risk-detail-chart-tabs"
          :value="currentChartTabsValue"
          :items="chartTabsItems"
          @item-click="handleChartTabsItemClick"
          v-if="showChartTabs"
        ></chart-tabs>
        <div class="charts-content trend" ref="trend" v-loading="chartLoading"></div>
        <legends :legendsVal="legendsVal" class="legends" v-if="dataType == '25'"></legends>
      </div>
    </div>
  </bi-page>
</template>

<script>
import BiPage from 'board/common/page'
import echarts from "echarts";
import legends from "./components/lengend.vue";
import { mySort, mySortByDate } from "@/utils";
import ChartTabs from './components/chart-tabs'
import ChartLoading from './components/chart-loading'
import BiCountySymptomList from 'board/common/county-symptom-list'

import { loadHealthySymptomData, loadBaseDiseaseData, loadBaseAssessmentData } from './api/charts'

import { getSymptomOptions, getDiseaseOptions } from '@/utils/data'

import {
  getSymptomData,
  getBaseDiseaseData,
  getPsyDiseaseData,
  getHealthySymptomData,
  getHealthyPsyDiseaseData,
  getHealthyBaseDiseaseData
} from "./api/charts";

let documentTitle = ''
export default {
  components: {
    BiPage,
    legends,
    ChartTabs,
    ChartLoading,
    BiCountySymptomList
  },
  data() {
    return {
      mapOptions: {},
      width: "72%",
      locationLoading: false,
      shenzhenLoading: false,
      result: {
        divisionDataVos: []
      },
      // 跳转标志
      dataType: "",
      legendList: [
        {
          name: "分类",
          id: 0
        },
        {
          name: "趋势",
          id: 1
        }
      ],
      legendText: "",
      titleList: {
        "10": "十大症状",
        "24": "基础疾病",
        "25": "心理疾病"
      },
      panelTitleList: {
        "10": "十大症状",
        "24": "基础疾病",
        "25": "心理疾病的风险"
      },
      legendIndex: -1,
      // 弹窗显隐
      dialogVisible: false,
      titleIcon: [
        require("../../assets/images/bar-icon.png"),
        require("../../assets/images/trend-icon.png")
      ],
      legendsVal: [
        {
          value: "高风险",
          color: "rgba(255, 139, 124, 1)"
        },
        {
          value: "中风险",
          color: "rgba(255, 194, 89, 1)"
        }
      ],
      // 心理疾病图例
      psychologicalVisible: false,
      chartLoading: false,
      currentChartTabsValue: null
    };
  },
  computed: {
    chartTabsItems () {
      let options = []
      if (this.dataType === '10') {
        options = getSymptomOptions()
      } else if (this.dataType === '24') {
        options = getDiseaseOptions()
      }
      return [{
        text: '全部',
        value: null
      }].concat(options)
    },
    showChartTabs () {
      return ["10", "24"].includes(this.dataType)
    }
  },
  async created() {
  },
  async mounted() {
    let result = null
    this.dataType = this.$route.query.dataType;
    this.locationLoading = true
    this.shenzhenLoading = true
    this.chartLoading = true
    documentTitle = window.document.title
    window.document.title = (this.titleList[this.dataType] || '') + '人员分布'
    if (this.dataType == "10") {
      result = await getSymptomData();
    } else if (this.dataType == "24") {
      result = await getBaseDiseaseData();
    } else {
      result = await getPsyDiseaseData();
    }
    this.result = result.data.data
    this.getDataByDataType()
    this.locationLoading = false
    this.shenzhenLoading = false
    this.chartLoading = false
  },
  methods: {
    handleDivisionItemClick ({ item }) {
      let typeToName = {
        10: "tenSymptomNum",
        24: "basicDiseaseNum",
        25: "psychicNum",
      };
      this.$router.push({
        path: "/gl/bulletinboard",
        query: {
          code: item.code,
          filterType: typeToName[this.dataType],
        },
      });
    },
    // 弹窗关闭
    handleDialogClosed() {
      this.dialogVisible = false;
      this.legendIndex = -1;
      this.psychologicalVisible = false;
    },

    // 点击右侧分类和趋势
    handleClickLegend(val) {
      // 点击相同，关闭弹窗
      if (this.legendIndex == val) {
        this.legendIndex = -1;
        this.dialogVisible = false;
      } else {
        this.legendIndex = val;
        this.dialogVisible = true;
        val == 0
          ? (this.legendText = "的隔离人数")
          : (this.legendText = "发展趋势");
        this.$nextTick(() => {
          this.getDataByDataType(val);
        });
      }
    },

    // 柱形图
    showBarCharts(xData, yData, yData2, rotate = 45, onBarClick) {
      // console.log("33333333333", xData, yData);
      const _this = this;
      let colorList = ["rgba(84, 166, 240, 1)", "rgba(234, 174, 70, 1)"];
      let option = {
        grid: {
          top: "25%",
          left: "3%",
          bottom: "0%",
          right: "5%",
          containLabel: true
        },
        tooltip: {
          show: true
        },
        animation: false,
        xAxis: [
          {
            type: "category",
            data: xData,
            axisTick: {
              // 这个没有的话，底下的圆圈会消失
              alignWithLabel: true,
              lineStyle: {
                // color: "transparent"
              }
            },
            nameTextStyle: {
              color: "#82b0ec"
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#ECECEC"
              }
            },
            axisLabel: {
              textStyle: {
                color: "#222328",
                fontSize: 10
              },
              rotate: rotate,
              margin: 15
            },
            splitLine: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            show: true,
            type: "value",
            name: "单位： 人",
            minInterval: 1,
            nameTextStyle: {
              color: "#A1A6BB",
              fontSize: 10,
              padding: [0, 0, 9, 0]
            },
            axisLabel: {
              textStyle: {
                color: "#868686",
                fontSize: 10,
                // fontWeight: "bold",
                fontFamily: "DIN Alternate"
              },
              margin: 7
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "transparent"
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#ECECEC"
              }
            }
          }
        ],
        series: [
          // 柱子
          {
            type: "bar",
            //silent: true,
            barWidth: "11",
            // barGap: "10%", // Make series be overlap
            // barCateGoryGap: "10%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 0.6, [
                      {
                        offset: 0,
                        color: "#EC7464",
                      },
                      {
                        offset: 1,
                        color: " rgba(236, 116, 100, 0.5)",
                      },
                    ])
                }
            },
            data: yData.map((item, index) => {
              // console.log("傻逼", item, index);
              let x = null;
              index % 2 == 0 ? (x = 1) : (x = 2);
              if (_this.dataType == "25") x = 3;
              return {
                value: item,
                label: {
                  show: true,
                  position: "top",
                  distance: 5,
                  // x == 1 ? colorList[0] : colorList[1]
                  color: function() {
                    // 这么写，文字颜色随主体变化，如果不写则是黑色
                    console.log("nishishabi ");
                  },
                  fontSize: 10
                }
              };
            })
          }
        ]
      };
      // 心理疾病+隔离人数，修改series
      if (this.dataType == "25" && this.legendIndex == "1") {
        option.series = [];
      }
      const chart = echarts.init(this.$refs.isolation)
      chart.setOption(option);
      console.log(chart.getOption())
      chart.on('click', (evt) => {
        if (evt.componentSubType === 'bar') {
          onBarClick && onBarClick({
            index: evt.dataIndex
          })
        } else if (evt.componentType === 'xAxis') {
          console.log(xData.indexOf(evt.value))
          onBarClick && onBarClick({
            index: xData.indexOf(evt.value)
          })
        }
      })
    },

    // 趋势线图
    showTrendCharts(xData, data1, data2, rotate = 45) {
      let option = {
        grid: {
          top: "20%",
          left: "3%",
          right: "8%",
          bottom: "2%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#ECECEC"
              }
            },
            axisLabel: {
              color: "#868686",
              margin: 10,
              rotate: rotate,
              padding: [0, 0, 0, 0],
              interval: 0,
              fontSize: 8
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            data: xData
          }
        ],

        yAxis: [
          {
            type: "value",
            min: 0,
            name: "单位：人",
            minInterval: 1,
            nameTextStyle: {
              color: "#A1A6BB",
              fontSize: 10,
              padding: [0, 0, 9, 6]
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#ECECEC"]
              }
            },
            axisLine: {
              show: false
            },
            axisLabel: {
              show: true,
              margin: 6,
              textStyle: {
                fontSize: 10,
                color: "#868686"
              }
            },
            axisTick: {
              show: false
            }
          }
        ],
        series: [
          {
            name: "高风险",
            type: "line",
            smooth: true, //是否平滑
            showAllSymbol: true,
            // symbol: 'image://./static/images/guang-circle.png',
            symbol: "circle",
            symbolSize: 7,
            lineStyle: {
              normal: {
                color: "rgba(102, 182, 255, 1)",
                shadowColor: "rgba(0, 0, 0, 0)",
                shadowBlur: 0,
                shadowOffsetY: 2,
                shadowOffsetX: 2
              }
            },
            label: {
              show: true,
              position: "top",
              textStyle: {
                color: "rgba(102, 182, 255, 1)",
                fontSize: 10
              }
            },
            itemStyle: {
              color: "#fff",
              borderColor: "rgba(102, 182, 255, 1)",
              borderWidth: 2,
              shadowColor: "rgba(102, 182, 255, 1)",
              shadowBlur: 5
              // shadowOffsetY: 2,
              // shadowOffsetX: 2
            },
            tooltip: {
              show: false
            },
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0.4,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(102, 182, 255, 1)"
                  },
                  {
                    offset: 1,
                    color: "rgba(102, 182, 255, 0.1)"
                  }
                ],
                global: false // 缺省为 false
              }
            },
            // data: [502, 205, 332, 281, 395, 214]
            data: data1
          }
        ]
      };
      console.log(this.dataType, this.legendIndex);
      // 心理疾病+隔离人数，两条折线，修改series
      if (this.dataType == "25") {
        // console.log('111111111');
        option.series.push({
          name: "低风险",
          type: "line",
          smooth: true, //是否平滑
          showAllSymbol: true,
          // symbol: 'image://./static/images/guang-circle.png',
          symbol: "circle",
          symbolSize: 7,
          lineStyle: {
            normal: {
              color: "rgba(255, 194, 89, 1)",
              shadowColor: "rgba(0, 0, 0, 0)",
              shadowBlur: 0,
              shadowOffsetY: 2,
              shadowOffsetX: 2
            }
          },
          label: {
            show: true,
            position: "top",
            textStyle: {
              color: "rgba(255, 194, 89, 1)",
              fontSize: 10
            }
          },
          itemStyle: {
            color: "#fff",
            borderColor: "rgba(255, 194, 89, 1)",
            borderWidth: 2,
            shadowColor: "rgba(255, 194, 89, 1)",
            shadowBlur: 5
            // shadowOffsetY: 2,
            // shadowOffsetX: 2
          },
          tooltip: {
            show: false
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0.4,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(255, 194, 89, 1)"
                },
                {
                  offset: 1,
                  color: "rgba(255, 194, 89, 0.1)"
                }
              ],
              global: false // 缺省为 false
            }
          },
          // data: [502, 205, 332, 281, 395, 214]
          data: data2
        });
        option.series[0].lineStyle.normal.color = "rgba(255, 139, 124, 1)";
        option.series[0].label.textStyle.color = "rgba(255, 139, 124, 1)";
        option.series[0].itemStyle.shadowColor = "rgba(255, 139, 124, 1)";
        option.series[0].itemStyle.borderColor = "rgba(255, 139, 124, 1)";
        option.series[0].areaStyle.color.colorStops[0].color =
          "rgba(255, 139, 124, 1)";
        option.series[0].areaStyle.color.colorStops[1].color =
          "rgba(255, 139, 124, 0.1)";
        this.psychologicalVisible = true;
      }
      console.log(option.series.length);
      echarts.init(this.$refs.trend).setOption(option);
    },

    // 根据路由的dataType值
    async getDataByDataType() {
      switch (this.dataType) {
        // 十大症状
        case "10":
          let { tenClassifyDayVos, tenClassifyVos } = this.result;
          tenClassifyVos = mySort(tenClassifyVos, "value", 0);
          // 折线图
          let tenClassifyDayXdata = tenClassifyDayVos.map(item =>
            item.key.substring(5, 10)
          );
          let tenClassifyDayYdata = tenClassifyDayVos.map(item => item.value);
          // 柱形图
          let tenClassifyVosXdata = tenClassifyVos.map(item => item.key);
          let tenClassifyVosYdata = tenClassifyVos.map(item => item.value);
          this.showBarCharts(tenClassifyVosXdata, tenClassifyVosYdata, null, undefined, ({ index }) => {
            const item = tenClassifyVos[index]
            if (!item || !item.code) {
              return
            }
            this.$router.push({
              path: '/riskList',
              query: {
                sourceType: 'symptomChart',
                dataType: item.code,
                title: `${item.key}`
              }
            })
          });
          this.refreshSymptomChatData();
          break;
        // 基础疾病
        case "24":
          let { basicClassifyDayVos, basicClassifyVos } = this.result;
          basicClassifyVos = mySort(basicClassifyVos, "value", 0);
          // 折线图
          let basicClassifyDayVosXdata = basicClassifyDayVos.map(item =>
            item.key.substring(5, 10)
          );
          let basicClassifyDayVosYdata = basicClassifyDayVos.map(
            item => item.value
          );
          // 柱形图
          let basicClassifyVosXdata = basicClassifyVos.map(item => item.key);
          let basicClassifyVosYdata = basicClassifyVos.map(item => item.value);
          this.showBarCharts(basicClassifyVosXdata, basicClassifyVosYdata, null, undefined, ({ index }) => {
            const item = basicClassifyVos[index]
            if (!item || !item.code) {
              return
            }
            const code = Math.min(item.code, 14)
            this.$router.push({
              path: '/riskList',
              query: {
                sourceType: 'diseaseChart',
                dataType: code,
                title: `${item.key}`
              }
            })
          });
          this.refreshSymptomChatData();
          break;
        // 心理疾病
        case "25":
          let { heartClassifyVos, heartClassifyDayVos } = this.result;
          let { high, medium } = heartClassifyDayVos;
          // 折线图
          let xdata = high.map(item => item.key.substring(5, 10));
          let highYdata = high.map(item => item.value);
          let mediumYdata = medium.map(item => item.value);
          // 柱形图
          let heartClassifyVosXdata = heartClassifyVos.map(item => item.key);
          let heartClassifyVosYdata = heartClassifyVos.map(item => item.value);
          this.showBarCharts(
            heartClassifyVosXdata,
            heartClassifyVosYdata,
            [],
            0,
            ({ index }) => {
              const item = heartClassifyVos[index]
              if (!item || !item.code) {
                return
              }
              this.$router.push({
                path: '/riskList',
                query: {
                  sourceType: 'psychicChart',
                  dataType: item.code,
                  title: `${item.key}`
                }
              })
            }
          );
          this.refreshSymptomChatData();
          break;
        default:
          console.log("");
      }
    },
    handleChartTabsItemClick ({ item }) {
      this.currentChartTabsValue = item.value
      this.refreshSymptomChatData({
        type: item.value
      })
    },
    refreshSymptomChatData (params) {
      this.chartLoading = true
      let queryFn = null
      if (this.dataType == "10") {
        queryFn = loadHealthySymptomData
      } else if (this.dataType == "24") {
        queryFn = loadBaseDiseaseData
      } else {
        queryFn = loadBaseAssessmentData
      }
      return queryFn(params).then(data => {
        let tenClassifyDayVos = data;
        tenClassifyDayVos = mySortByDate(tenClassifyDayVos, "date", 1);
        // 折线图
        let tenClassifyDayXdata = tenClassifyDayVos.map((item) => item.date);
        // 最多两条线，心理疾病
        let chartData = []
        if (data && data.length) {
          const { date, ...fields } = data[0]
          chartData = Object.keys(fields).reduce((rs, v) => {
            const nextData = data.map(vv => {
              return vv[v]
            })
            rs.push(nextData)
            return rs
          }, [])
        }
        this.showTrendCharts(
          tenClassifyDayXdata,
          chartData[0],
          chartData[1],
          45
        );
      }).finally(() => {
        this.chartLoading = false
      })
    }
  },
  beforeRouteLeave (to, from, next) {
    window.document.title = documentTitle
    next()
  }
};
</script>

<style lang="scss" scoped>
.risk-detail-page__main{
  padding: 16px 12px 0;
}
.risk-detail-page__symptom{
  margin-bottom: 15px;
}
.risk-detail-page {
  position: relative;
  box-sizing: border-box;

  .isolation-wrapper,
  .trend-wrapper {
    height: 265px;
    padding: 13px 0 0 15px;
    background: #ffffff;
    box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    /deep/ .el-loading-mask{
      position: absolute;
    }
  }
  .isolation-wrapper {
    margin: 0 0 15px 0;
    .title-wrapper {
      background: url("../../assets/images/bar-icon.png") no-repeat;
      background-size: contain;
    }
  }
  .trend-wrapper {
    position: relative;
    height: 320px;
    padding-right: 15px;
    display: flex;
    flex-direction: column;
    .title-wrapper {
      background: url("../../assets/images/trend-icon.png") no-repeat;
      background-size: contain;
    }
    .charts-content{
      flex: 1;
      min-height: 0;
      height: auto;
      padding-bottom: 10px;
    }
  }

  .title-wrapper {
    height: 20px;
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 18px;
    color: #1d1f24;
    p {
      text-indent: 27px;
    }
  }

  .charts-content {
    width: 318px;
    height: 220px;
    // background: pink;
  }

  .legends {
    position: absolute;
    top: 44px;
    right: 18px;
  }
}
.risk-detail-chart-tabs{
  margin-top: 12px;
}
</style>
